<template>
  <view class="edit-address-page">
    <van-cell-group>
      <van-field
        :value="name"
        label="姓名"
        placeholder="请输入姓名"
        @change="handleChangeName"
      ></van-field>

      <van-field
        :value="mobile"
        center
        label="手机"
        placeholder="请输入手机号"
        @change="handleChangeMobile"
      >
        <image
          @click="handleSelectPhone"
          src="/static/image/address-book.png"
          slot="right-icon"
          class="address-book-icon"
        ></image>
      </van-field>

      <van-field center label="省市区" placeholder="请选择省市区">
        <picker
          :value="pickerVal"
          mode="region"
          slot="input"
          class="picker-wrap"
          @change="handleChangePicker"
        >
          <view class="picker-contnet">
            <view class="cur-select" v-if="provinceCityDistrict">{{
              provinceCityDistrict
            }}</view>

            <view class="default" v-else>请选择省市区</view>
          </view>
        </picker>
        <image
          @click="handleSelectAddress"
          src="/static/image/site.png"
          slot="right-icon"
          class="site-icon"
        ></image>
      </van-field>

      <van-field
        :value="name_address"
        label="详细地址"
        readonly
        placeholder="请选择详细地址"
      >
        <van-button
          slot="button"
          size="small"
          color="#FF9600"
          @click="handleToSelectDetail"
          >{{ name_address ? "去修改" : "去选择" }}</van-button
        >
      </van-field>

      <van-field
        :value="door_number"
        label="门牌号"
        placeholder="请输入门牌号"
        @change="handleChangeDoorNumber"
      ></van-field>
    </van-cell-group>

    <view class="bottom-btn">
      <van-button
        color="#FF9600"
        custom-class="button-cus"
        type="primary"
        @click="handleSaveAddress"
        >保存</van-button
      >
    </view>

    <van-dialog id="van-dialog" />
    <van-toast id="van-toast" />
  </view>
</template>

<script>
const app = getApp();
import Dialog from "wxcomponents/vant/dialog/dialog";
import Toast from "wxcomponents/vant/toast/toast";
import Auth from "@/common/permission/index.js";

export default {
  data() {
    return {
      isEdit: false,
      id: "",
      name: "",
      mobile: "",
      province: "",
      city: "",
      district: "",
      name_address: "",
      door_number: "",
      location: "",
      provinceCityDistrict: "",
      pickerVal: ["湖南省", "长沙市", "开福区"],
      source: "", // 跳转来源
      type: "", // 操作类型
      curLatitude: "",
      curLongitude: "",
      isFirstEnter: false,
    };
  },
  methods: {
    handleChangeName(res) {
      const { detail } = res;

      this.name = detail;
    },
    handleChangeDoorNumber(res) {
      const { detail } = res;

      this.door_number = detail;
    },
    handleSaveAddress() {
      const {
        name,
        mobile,
        pickerVal,
        name_address,
        door_number,
        location,
        id,
        source,
        type,
      } = this;

      if (!name) {
        Toast("请输入姓名");
        return;
      }
      if (!mobile) {
        Toast("请输入手机");
        return;
      }
      if (!pickerVal || !pickerVal.length) {
        Toast("请选择省市区");
        return;
      }
      if (!name_address) {
        Toast("请输入详细地址");
        return;
      }
      if (!door_number) {
        Toast("请输入门牌号");
        return;
      }

      let result = {
        a_id: id || "",
        name,
        mobile,
        province: pickerVal[0],
        city: pickerVal[1],
        district: pickerVal[2],
        name_address,
        door_number,
        location,
      };
      Toast.loading({
        message: "加载中",
        mask: false,
        duration: 0,
        zIndex: 9999999,
        forbidClick: true,
      });
      app.request(result, "/api/logistics/address/create_add").then((res) => {
        const { code, data, msg } = res;

        if (code === 1) {
          if (source === "sendPage") {
            const eventChannel = this.getOpenerEventChannel();
            if (!id) {
              result["id"] = data;
            } else {
              result["id"] = id;
            }
            if (type === "send") {
              eventChannel.emit("editSendInfo", {
                ...result,
              });
            } else if (type === "receiving") {
              eventChannel.emit("editReceivingInfo", {
                ...result,
              });
            }
            uni.navigateBack();
          } else if (source === "addressManagementPage") {
            Toast(msg);
            uni.navigateBack();
          }
        } else {
          Toast(msg);
        }
      });
    },

    handleChangeMobile(res) {
      const { detail } = res;

      this.mobile = detail;
    },

    handleSelectPhone() {
      const that = this;

      uni.chooseContact({
        success(res) {
          console.log(res);
          const { phoneNumber } = res;

          that.mobile = phoneNumber;
        },
      });
    },
    async handleSelectAddress() {
      const that = this;
      let authState = await new Auth("userLocation").check();
      authState &&
        uni.getLocation({
          type: "wgs84",
          success(res) {
            const { latitude, longitude } = res;
            that.curLatitude = latitude;
            that.curLongitude = longitude;
            app.globalData.latitude = latitude;
            app.globalData.longitude = longitude;
            that.getLocationInfo(); //逆地址解析
          },
          fail(res) {},
        });
    },
    //逆坐标解析
    async getLocationInfo() {
      //   当前定位
      const { curLatitude, curLongitude } = this;
      if (curLatitude && curLongitude) {
        const that = this;
        let location = `${curLatitude},${curLongitude}`;
        let key = app.globalData.mapKey;
        Toast.loading({
          message: "定位中",
          mask: false,
          duration: 0,
          zIndex: 9999999,
          forbidClick: true,
        });
        const res = await uni.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1?location=${location}&key=${key}`,
        });
        const { status, message, result } = res.data;
        if (status === 0) {
          const { address_component, formatted_addresses } = result;
          const { province, city, district } = address_component;
          const { recommend } = formatted_addresses;
          that.pickerVal = [province, city, district];
          that.provinceCityDistrict = `${province}${city}${district}`;
          that.location = location;
          that.name_address = recommend;
          Toast.clear();
        } else {
          console.log("%c逆地址解析失败", "color:green;background:yellow");
        }
      }
    },
    handleSave() {},
    handleToSelectDetail() {
      const that = this;
      let arr = [];

      if (this.location) {
        arr = this.location.split(",");
      } else {
        Toast("请先选择省市区");
        return;
      }
      uni.chooseLocation({
        latitude: arr[0],
        longitude: arr[1],
        success: (res) => {
          console.log(res);

          if (!res.name || !res.address || !res.latitude || !res.longitude)
            return;
          let addressObj = {
            title: res.name,
            address: res.address,
            latitude: res.latitude,
            longitude: res.longitude,
          };
          that.name_address = res.name;
          that.location = `${res.latitude},${res.longitude}`;

          let location = `${res.latitude},${res.longitude}`;
          let key = app.globalData.mapKey;
          let url = `https://apis.map.qq.com/ws/geocoder/v1?location=${location}&key=${key}`;

          uni.request({
            url: url,
            success: (res) => {
              const { status, message, result } = res.data;

              if (status === 0) {
                const { address_component } = result;
                const { province, city, district } = address_component;

                that.pickerVal = [province, city, district];
                that.provinceCityDistrict = `${province}${city}${district}`;
              }
            },
          });
        },
      });
    },
    handleChangePicker(res) {
      const { detail } = res;
      const { value } = detail;

      this.pickerVal = value;
      this.provinceCityDistrict = `${value[0]}${value[1]}${value[2]}`;
      let key = app.globalData.mapKey;
      let url = `https://apis.map.qq.com/ws/geocoder/v1/?address=${this.provinceCityDistrict}&key=${key}`;

      uni.request({
        url: url,
        success: (res) => {
          const { status, message, result } = res.data;

          if (status === 0) {
            const { location } = result;

            this.location = `${location.lat},${location.lng}`;
            this.name_address = "";
          }
        },
      });
    },
  },
  onLoad(res) {
    console.log(res);
    const {
      id,
      name,
      mobile,
      province,
      city,
      district,
      name_address,
      door_number,
      location,
      source,
      type,
    } = res;

    this.source = source;
    this.type = type;
    if (id) {
      this.isEdit = true;
      this.id = id;
      this.name = name;
      this.mobile = mobile;
      this.province = province;
      this.city = city;
      this.district = district;
      this.provinceCityDistrict = province + city + district;
      this.name_address = name_address;
      this.door_number = door_number;
      this.location = location;
      this.pickerVal = [province, city, district];
    }

    this.curLatitude = app.globalData.latitude;
    this.curLongitude = app.globalData.longitude;

    if (this.type === "edit") {
      uni.setNavigationBarTitle({
        title: "编辑地址", // 要设置的新标题
      });
    }
  },
  onShow() {
    const KEY_FIRST_ENTER = "firstKey1";
    const firstKey = uni.getStorageSync(KEY_FIRST_ENTER);
    if (!firstKey) {
      // 如果没有找到标志，则表示是第一次进入
      uni.setStorageSync(KEY_FIRST_ENTER, true); // 设置标志，标记已进入过
    } else {
      this.handleSelectAddress();
    }
  },
};
</script>

<style lang="scss">
.edit-address-page {
  position: relative;
  min-height: 100vh;
  background-color: #f2f2f2;

  .van-field__icon-container {
    display: flex;
    align-items: center;
  }

  .address-book-icon {
    width: 40rpx;
    height: 40rpx;
  }

  .site-icon {
    width: 40rpx;
    height: 46rpx;
  }

  .bottom-btn {
    width: 100%;
    padding: 20rpx;
    box-sizing: border-box;
    .button-cus {
      width: 100%;
    }
  }

  .detail-field {
    color: #646566;
    .input-class {
      color: #646566;
    }
  }

  .picker-wrap {
    width: 100%;
    height: 100%;
    .picker-contnet {
      width: 100%;
      height: 48rpx;
      .placeholder {
        color: #cbcfd2;
      }
      .cur-select {
        color: #323233;
      }
      .default {
        color: #c8cac9;
      }
    }
  }
}
</style>
